package com.bdth.bdthiss.jsoup;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文件管理工具类
 */
public class FileTools {
    private static Logger logger = LoggerFactory.getLogger(FileTools.class);
    /**
     *创建文件夹
     * @param filePath
     */
    public static void createDir(String filePath){
        File file = new File(filePath);
        if(file.exists()){
            if(!file.isDirectory()){
                //不能用mkdir，如果是深路径就创建失败
                file.mkdirs();
            }
        }else{
            file.mkdirs();
        }
    }

    /**
     * 根据url获取文件名称
     * @param src
     * @return
     */
    public static String getFileName(String src){
        String temp = src.substring(src.lastIndexOf("/") + 1);
        String suffixes="avi|mpeg|3gp|mp3|mp4|wav|jpeg|gif|jpg|png|apk|exe|pdf|rar|zip|docx|doc";
        Pattern pat=Pattern.compile("[\\w]+[\\.]("+suffixes+")");//正则判断
        Matcher mc=pat.matcher(temp);//条件匹配
        while(mc.find()){
            String fileName = mc.group();
            return fileName;
        }
        return null;
    }

    /**
     * 改进反扒图片URL
     * @param url
     * @return
     */
    public static String getRealUrl(String url){
        if(url.startsWith("http")) {
            return url;
        }else {
            return url.startsWith("//")?"http:" + url : "http://" + url;
        }
    }

    /**
     * 根据图片src，下载图片放入相应文件夹
     * @param src
     * @param dir
     */
    public static String downPic(String src,String dir){
        URL url;
        String fileName = "";
        try {
            url = new URL(src);
            URLConnection uri = url.openConnection();
            // 设置5秒的相应时间
            uri.setConnectTimeout(5 * 1000);
            // 获取数据流
            InputStream is = null;
            try {
                is = uri.getInputStream();
            }catch (Exception e){
                return null;
            }
            //创建文件夹
            FileTools.createDir(dir);
            fileName = FileTools.getFileName(src);
            // 写入数据流
            OutputStream os = new FileOutputStream(new File(dir, fileName));
            byte[] buf = new byte[3072];
            int i = 0;
            while ((i = is.read()) != -1) {
                os.write(i);
            }
            os.close();
        } catch (MalformedURLException e1) {
            logger.error(e1.getMessage());
        } catch (IOException e1) {
            logger.error(e1.getMessage());
        }
        return fileName;
    }

    public static List<String> getDirFilesName(String url,File file) {
        List<String> result = new ArrayList<>();
        File[] list = file.listFiles();
        for (File f : list) {
            if (!f.isDirectory()) {
                result.add((url==null?"":url)+f.getName());
            }
        }
        return result;
    }

    public static void main(String args[]){
        /**
         * 下载图片测试
         */
//        URL url;
//        String src ="https://www.officemate.cn/public/images/14/80/46/2bde9ef560306c62a2c6e4ffb5d38caa6a5c02ea.jpg?1574832729#h";
//        String dir = "C:\\jsoup\\images";
//        downPic(src,dir);
        /**
         * 读取文件夹所有文件名称
         * 组成图片url
         */
        String dir = "C:\\xampp\\htdocs\\www.bdthmall.com\\upload\\warrant\\";
        List<String> filenames = getDirFilesName("http://39.105.26.214:8081/upload/warrant/",new File(dir));
        filenames.stream().forEach(name-> System.out.println(name));
    }
}
